package cn.wolfcode.thread;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁 读读不互斥
 * 应用场景:读远远大于写
 * 特点:
 *      多个读者可以同时进行读
 *      写者必须互斥（只允许一个写者写，也不能读者写者同时进行）
 *      写者优先于读者（一旦有写者，则后续读者必须等待，唤醒时优先考虑写者）
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();

        //写线程
        new Thread(new Runnable() {
            public void run() {
                readWriteLockDemo.set(new Random().nextInt(100));
            }
        }).start();

        //读线程
        for (int i = 0; i <100 ; i++) {
            new Thread(new Runnable() {
                public void run() {
                    readWriteLockDemo.get();
                }
            }).start();

        }
    }

    }
class ReadWriteLockDemo{
    private int num;
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void get(){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName());
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void set(int num){
        readWriteLock.writeLock().lock();
        try {
            System.out.println("write"+Thread.currentThread().getName());
            this.num = num;

        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

}
